package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.Contact;
import com.kaishengit.util.db.DBHelp;
import com.kaishengit.util.db.RowMapper;

public class ContactDao {

	public DBHelp<Contact> db = new DBHelp<Contact>();
	
	public void save(Contact contact) {
		StringBuilder sql = new StringBuilder();
		sql.append("INSERT INTO `t_contact` ");
		sql.append("(`id`,`name`,`company`,`mobile`,`tel`,`email`,`address`,`homepage`,`weibo`,`description`) ");
		sql.append("VALUES ");
		sql.append("(?,?,?,?,?,?,?,?,?,?)");
		db.executeSQL(sql.toString(), contact.getId(),contact.getName(),contact.getCompany(),contact.getMobile(),contact.getTel(),contact.getEmail(),contact.getAddress(),contact.getHomepage(),contact.getWeibo(),contact.getDescription());
	}
	
	public void del(int id) {
		String sql = "delete from t_contact where id = ?";
		db.executeSQL(sql, id);
	}
	
	public void update(Contact contact) {
		StringBuilder sql = new StringBuilder();
		sql.append("UPDATE `t_contact` ");
		sql.append("SET `name` = ? ,`company` = ? ,`mobile` = ? ,`tel` = ? ,`email` = ? ,`address` = ? ,`homepage` = ? ,`weibo` = ? ,`description` = ?");
		sql.append("WHERE");
		sql.append("`id` = ?");
		db.executeSQL(sql.toString(),contact.getName(),contact.getCompany(),contact.getMobile(),contact.getTel(),contact.getEmail(),contact.getAddress(),contact.getHomepage(),contact.getWeibo(),contact.getDescription(), contact.getId());
	}
	
	public List<Contact> findAll() {
		String sql = "select `id`,`name`,`company`,`mobile`,`tel`,`email`,`address`,`homepage`,`weibo`,`description` from t_contact";
		return db.executeQueryToList(sql, new ContactRowMapper());
	} 
	
	private class ContactRowMapper implements RowMapper<Contact> {

		public Contact mapRow(ResultSet rs) throws SQLException {
			Contact contact = new Contact();
			contact.setId(rs.getInt("id"));
			contact.setName(rs.getString("name"));
			contact.setCompany(rs.getString("company"));
			contact.setMobile(rs.getString("mobile"));
			contact.setTel(rs.getString("tel"));
			contact.setEmail(rs.getString("email"));
			contact.setAddress(rs.getString("address"));
			contact.setHomepage(rs.getString("Homepage"));
			contact.setWeibo(rs.getString("weibo"));
			contact.setDescription(rs.getString("description"));
			return contact;
		}
		
	} 
	
}
